﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using AliFox.BaseService.BaseData.DataDictionaryManagement.Dto;
using AliFox.BaseService.Permissions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using Volo.Abp;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace AliFox.BaseService.BaseData.DataDictionaryManagement;

[Authorize(BaseServicePermissions.DataDictionary.Default)]
public class DictionaryAppService(IRepository<DataDictionary, Guid> repository)
    : ApplicationService, IDictionaryAppService
{
    public async Task<PagedResultDto<DictionaryDto>> GetAll(GetDictionaryInputDto input)
    {
        var query = (await repository.GetQueryableAsync())
            .WhereIf(!string.IsNullOrWhiteSpace(input.Filter), _ => _.Name.Contains(input.Filter) || _.Description.Contains(input.Filter));

        var items = await query.OrderBy(input.Sorting ?? "Name")
            .Skip(input.SkipCount)
            .Take(input.MaxResultCount)
            .ToListAsync();

        var totalCount = await query.CountAsync();

        var dots = ObjectMapper.Map<List<DataDictionary>, List<DictionaryDto>>(items);
        return new PagedResultDto<DictionaryDto>(totalCount, dots);
    }

    public async Task<DictionaryDto> Get(Guid id)
    {
        var res = await repository.GetAsync(id);
        return ObjectMapper.Map<DataDictionary, DictionaryDto>(res);
    }

    [Authorize(BaseServicePermissions.DataDictionary.Create)]
    public async Task<DictionaryDto> Create(CreateOrUpdateDictionaryDto input)
    {
        var exist = await repository.FirstOrDefaultAsync(_ => _.Name == input.Name);

        if(exist != null)
        {
            throw new BusinessException("名称：" + input.Name + "字典已存在");
        }

        var dict = new DataDictionary(GuidGenerator.Create(), input.Name, input.Description);

        var res = await repository.InsertAsync(dict);
        return ObjectMapper.Map<DataDictionary, DictionaryDto>(res);
    }

    [Authorize(BaseServicePermissions.DataDictionary.Update)]
    public async Task<DictionaryDto> Update(Guid id, CreateOrUpdateDictionaryDto input)
    {
        var dict = await repository.GetAsync(id);

        dict.Name = input.Name;
        dict.Description = input.Description;

        await repository.UpdateAsync(dict);

        return ObjectMapper.Map<DataDictionary, DictionaryDto>(dict);
    }

    [Authorize(BaseServicePermissions.DataDictionary.Delete)]
    public async Task Delete(List<Guid> ids)
    {
        foreach(var id in ids)
        {
            await repository.DeleteAsync(id);
        }
    }
}